package pl.nith.battleships.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import pl.nith.battleships.managers.GameStateManager.GameState;
import pl.nith.battleships.managers.Manager;

public class ConnectionHandler extends Thread
{
	private Socket				connection	= null;
	private BufferedReader		incoming	= null;
	private PrintWriter			outgoing	= null;

	private BattleshipProtocol	protocol	= new BattleshipProtocol();

	private String				fromClient	= "";

	public ConnectionHandler(Socket connection)
	{
		super("BattleshipConnectionThread");
		this.connection = connection;
	}

	public void SendMessage(String message)
	{
		outgoing.println(message);
	}

	public void run()
	{
		try
		{
			if (connection.isConnected()
							&& Manager.getGMS().currentGameState == GameState.GAME_NOT_STARTED)
			{
				Manager.getGMS().currentGameState = GameState.CONNECTED;
				Manager.getMWV().getMainWindow().getPubBoardSurface().changeButtonToSetShips();
			}

			incoming = new BufferedReader(new InputStreamReader(
							connection.getInputStream()));
			outgoing = new PrintWriter(connection.getOutputStream(), true);

			while ((fromClient = incoming.readLine()) != null)
			{
				protocol.processCommand(fromClient);
				if (fromClient.equals("Bye")) break;
			}

			outgoing.close();
			incoming.close();
			connection.close();
		}
		catch (IOException e)
		{
			System.err.println(e.getMessage());
		}
	}
}
